import os
import shutil

import openpyxl

# C D E F G H I

# 创建新工作簿
# workbook = openpyxl.Workbook()

# 获取默认工作表
# sheet = workbook.active

# 写入数据到单元格
# for i in range(10000):
#    sheet.cell(row=i + 1, column=1, value=i)
# sheet[cell] = 'Hello'


# 保存工作簿
# workbook.save('new_example.xlsx')


# def get_files(root_dir):
#     files = os.listdir(root_dir)
#     sub_dirs = []
#     for f in files:
#         sub_dir = os.path.join(root_dir, f)
#         if os.path.isfile(sub_dir):
#             yield sub_dir
#             continue
#         sub_dirs.append(sub_dir)
#     for sub_dir in sub_dirs:
#         for f in get_files(sub_dir):
#             yield f


# def save_excel(file_name, path):
#     # 创建新工作簿
#     workbook = openpyxl.Workbook()
#
#     # 获取默认工作表
#     sheet = workbook.active
#
#     # 写入数据到单元格
#     for i, f in enumerate(get_files(path)):
#         sheet.cell(row=i + 1, column=1, value=f)
#
#     # 保存工作簿
#     workbook.save(file_name)


# data = [
#     {'name': 'f.xlsx', 'path': r'f:\影视'},
#     {'name': 'g.xlsx', 'path': r'g:\影视'},
#     {'name': 'h.xlsx', 'path': r'h:\影视'},
#     {'name': 'i.xlsx', 'path': r'i:\zhangle\影视'}
# ]
#
# for item in data:
#     save_excel(item.get('name'), item.get('path'))


# def load_date(file):
#     # 打开工作簿
#     workbook = openpyxl.load_workbook(file)
#
#     # 获取工作表
#     sheet = workbook['Sheet']
#
#     # 读取单元格数据
#     for i in range(sheet.max_row):
#         cell_value = sheet.cell(i + 1, 1).value
#         yield cell_value


# # 创建新工作簿
# workbook = openpyxl.Workbook()
#
# # 获取默认工作表
# sheet = workbook.active
#
# # 写入数据到单元格
# cnt = 0
#
# for i in data:
#     for item in load_date(i.get('name')):
#         sheet.cell(row=cnt + 1, column=1, value=item)
#         cnt = cnt + 1
#
# # 保存工作簿
# workbook.save("all.xlsx")

import hashlib
from itertools import takewhile, repeat


class Md5:
    filename = ''

    def get_md5(self):
        with open(self.filename, "rb") as f:
            bytes = f.read()  # read file as bytes
            readable_hash = hashlib.md5(bytes).hexdigest()
            return readable_hash

    def md5_sum4(self):
        buffer = 1024 * 1024
        with open(self.filename, "rb") as f:
            buf_gen = takewhile(lambda x: x, (f.read(buffer) for _ in repeat(None)))
            md5 = hashlib.md5()

            for line in buf_gen:
                md5.update(line)
        f_md5 = md5.hexdigest()
        return f_md5

    def file_size(self):
        import os
        stats = os.stat(self.filename)
        return stats.st_size


# md5 = Md5()

# 打开工作簿
# workbook = openpyxl.load_workbook("all.xlsx")

# 获取工作表
# sheet = workbook['Sheet']

# file_size_dict = dict()

# 读取单元格数据
# for i in range(sheet.max_row):
#     cell_value = sheet.cell(i + 1, 1).value
#     md5.filename = cell_value
#     print(md5.filename)
#     print(md5.file_size())
# if md5.file_size() in file_size_dict.keys():
#     file_size_dict.get(md5.file_size()).append(md5.filename)
# else:
#     file_size_dict[md5.file_size()] = [md5.filename]

# for key in file_size_dict.keys():
#     if len(file_size_dict[key]) > 1:
#         if (int(key) / 1024 / 1024 / 1024) < 1:
#             continue
#         print("---------------%s---------------" % key)
#         for file in file_size_dict[key]:
#             print(file)

# total_size = 0
# # 读取单元格数据
# for i in range(sheet.max_row):
#     cell_value = sheet.cell(i + 1, 1).value
#     md5.filename = cell_value
#     total_size += md5.file_size()
#
# print(str(total_size / 1024 / 1024 / 1024) + " GB")


def getdirsize(dir):
    size = 0
    for root, dirs, files in os.walk(dir):
        size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
    return size


class FileFootman:
    jiaocheng_path = r'i:\zhangle\教程'

    movie_path = r'f:\影视\电影'

    # 教程子目录大小
    jiaocheng_size_list = []

    # 电影文件大小
    moive_size_list = []

    def test(self):
        print("test")

    # 把教程换到F盘, 把电影换到I盘

    def get_sub_folder_size(self, root_path):
        # 获取F教程子目录文件夹大小

        sub_list = os.listdir(root_path)

        sub_size_dict = dict()
        for sub in sub_list:
            path = os.path.join(root_path, sub)
            sub_size = getdirsize(path) / 1024 / 1024  # MB
            sub_size_dict[path] = sub_size
            # print("folder name: %s\t size: %d" % (path, sub_size))
        return sub_size_dict

    def get_jiaocheng_sub_folder_size(self):
        # 获取F教程子目录文件夹大小
        sub_size_dict = self.get_sub_folder_size(self.jiaocheng_path)
        self.jiaocheng_size_list = sorted(sub_size_dict.items(), key=lambda d: d[1], reverse=False)
        return self.jiaocheng_size_list

    def get_movie_size(self):
        # 计算电影文件大小
        sub_size_dict = self.get_sub_folder_size(self.movie_path)
        # 排序
        self.moive_size_list = sorted(sub_size_dict.items(), key=lambda d: d[1], reverse=False)
        return self.moive_size_list

    # 计算F子文件夹对应多少个电影
    def handle_jiaocheng_movie_mapping(self):
        for item in self.jiaocheng_size_list:
            value = item[1]
            movie_total = 0
            movie_list = []

            moive_size_list = self.moive_size_list

            while len(moive_size_list) > 0:
                movie = moive_size_list.pop()
                movie_list.append(movie)
                movie_total += movie[1]
                if value <= movie_total:
                    break
            # 打印交换任务列表
            print("-----------------------------------------")
            print("教程目录:%s" % item[0])
            print("教程目录大小:%d" % item[1])
            print("电影映射大小:%d" % movie_total)
            print("电影映射列表:")
            for m in movie_list:
                print(m)
            print("")

            # 进行交换
            jiaocheng_root_path_new = r'f:\教程\TMP'
            movie_root_path_new = r'i:\zhangle\影视\TMP'

            import shutil

            # 移动教程目录
            old_path = item[0]
            new_path = os.path.join(jiaocheng_root_path_new, os.path.basename(old_path))
            print(" * 移动教程 -> [ 从源目录:%s,到目标目录:%s ]" % (old_path, new_path))
            shutil.move(old_path, new_path)

            # 移动电影目录
            print(" * 移动电影目录 ***")
            for m in movie_list:
                old_path = m[0]
                new_path = os.path.join(movie_root_path_new, os.path.basename(old_path))
                print(" * 移动电影目录 -> [ 从源目录:%s,到目标目录:%s ]" % (old_path, new_path))
                shutil.move(old_path, new_path)
            break


footman = FileFootman()
footman.test()
footman.get_jiaocheng_sub_folder_size()
footman.get_movie_size()
#footman.handle_jiaocheng_movie_mapping()

shutil.move(r"f:\影视\电影\权利的游戏\美剧-冰与火之歌", r"i:\zhangle\影视\TMP\权利的游戏")